from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QIcon, QFont
from PyQt5.QtWidgets import QFileSystemModel, QMenu, QAction, QMessageBox
import shutil
from views.tree_view_method import CustomIconProvider
import os
from config.config import Config
from controllers.MyDialog import CustomInputDialog


class CustomFileSystemModel(QFileSystemModel):
    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.DisplayRole and index.column() == 0:
            # 获取原始文件名
            filename = QFileSystemModel.data(self, index, role)
            # 去掉文件名后缀
            return os.path.splitext(filename)[0]
        return QFileSystemModel.data(self, index, role)


class TreeView:
    def __init__(self, parent, treeView_ToolBar):
        self.parent = parent
        self.treeView_ToolBar = treeView_ToolBar
        self.scene = self.parent.scene
        self.model = CustomFileSystemModel()
        self.model.setIconProvider(CustomIconProvider())
        self.model.setRootPath(Config.data_path)
        self.treeView_ToolBar.setModel(self.model)
        self.treeView_ToolBar.setRootIndex(self.model.index(Config.data_path))
        self.treeView_ToolBar.setColumnHidden(1, True)  # 隐藏大小
        self.treeView_ToolBar.setColumnHidden(2, True)  # 隐藏类型
        self.treeView_ToolBar.setColumnHidden(3, True)  # 隐藏修改日期
        self.treeView_ToolBar.setIconSize(QSize(30, 30))
        self.treeView_ToolBar.header().hide()  # 隐藏标题栏

        font = QFont()
        font.setFamily("Microsoft YaHei")  # 设置字体家族
        font.setPointSize(16)  # 设置字体大小
        # font.setBold(True)  # 设置字体加粗
        self.treeView_ToolBar.setFont(font)


class TreeViewManager(TreeView):
    def __init__(self, parent):
        super(TreeViewManager, self).__init__(parent, parent.treeView_ToolBar)
        # 设置左键单击事件
        self.treeView_ToolBar.setContextMenuPolicy(Qt.CustomContextMenu)
        self.treeView_ToolBar.customContextMenuRequested.connect(self.show_context_menu)
        self.treeView_ToolBar.clicked.connect(self.handle_left_click)
        self.treeView_ToolBar.doubleClicked.connect(self.handle_double_left_click)
        self.open_file(os.path.join(Config.data_path, '自定义文件', '机动导弹.json'))

    def open_file(self, file_path):
        # 获取选择的文件的索引
        index = self.model.index(file_path)

        if index.isValid():
            # 展开父项
            self.treeView_ToolBar.expand(index.parent())
            # 选择文件
            self.treeView_ToolBar.setCurrentIndex(index)
            self.scene.load_nodes(self.model.filePath(index))

    def show_context_menu(self, pos):
        menu = QMenu(self.parent)
        action1 = QAction("新建文件", self.parent)
        action2 = QAction("新建文件夹", self.parent)
        action3 = QAction("删除文件", self.parent)
        menu.addAction(action1)
        menu.addAction(action2)
        menu.addAction(action3)
        action1.triggered.connect(lambda: self.handle_context_menu_action(1))
        action2.triggered.connect(lambda: self.handle_context_menu_action(2))
        action3.triggered.connect(lambda: self.handle_context_menu_action(3))
        menu.exec_(self.treeView_ToolBar.mapToGlobal(pos))

    def handle_context_menu_action(self, action_number):
        if action_number == 1:
            # 在当前目录下新建文件
            current_index = self.treeView_ToolBar.currentIndex()
            current_path = self.model.filePath(current_index)
            # 判断current_path是文件还是文件夹
            if os.path.isfile(current_path):
                current_path = os.path.dirname(current_path)
            # 用自定义dialog
            dialog = CustomInputDialog()
            file_name, ok = dialog.getText("文件名：")
            if ok and file_name:
                if '.' in file_name:
                    QMessageBox.warning(self.parent, "文件名错误", "文件名中不能包含 '.'")
                    return
                file_path = os.path.join(current_path, file_name + '.json')
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write('')

        elif action_number == 2:
            # 在当前目录下新建文件夹
            dialog = CustomInputDialog()
            current_index = self.treeView_ToolBar.currentIndex()
            current_path = self.model.filePath(current_index)
            if os.path.isfile(current_path):
                current_path = os.path.dirname(current_path)
            folder_name, ok = dialog.getText("文件夹名：")
            if ok and folder_name:
                folder_path = os.path.join(current_path, folder_name)
                os.makedirs(folder_path)

        elif action_number == 3:
            # 删除文件
            current_index = self.treeView_ToolBar.currentIndex()
            current_path = self.model.filePath(current_index)
            # 弹出一个对话框,用来确认删除
            message_box = QMessageBox()
            icon = QIcon(os.path.join(Config.svg_path, "notice.png"))
            message_box.setWindowIcon(icon)  # 设置窗口图标
            message_box.setWindowTitle("提示")  # 设置窗口标题
            message_box.setText(f"是否删除 {current_path.split('/')[-1]}?")  # 设置提示文本
            # 添加按钮
            message_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            message_box.setDefaultButton(QMessageBox.No)  # 默认选择为 No

            # 显示对话框并获取用户的选择
            reply = message_box.exec_()

            if reply == QMessageBox.Yes:
                if os.path.isfile(current_path):
                    os.remove(current_path)  # 删除文件
                elif os.path.isdir(current_path):
                    shutil.rmtree(current_path)  # 删除文件夹

    def handle_left_click(self, index):
        print(f"Left click on item: {self.model.filePath(index)}")

    def handle_double_left_click(self, index):
        print("index:", index)
        self.scene.load_nodes(self.model.filePath(index))
        print(f"Left Double click on item: {self.model.filePath(index)}")


class DataTreeViewManager(TreeView):
    def __init__(self, parent):
        super(DataTreeViewManager, self).__init__(parent, parent.treeView)
        # 设置左键单击事件
        self.treeView_ToolBar.clicked.connect(self.handle_left_click)
        self.treeView_ToolBar.doubleClicked.connect(self.handle_double_left_click)
        self.open_file(os.path.join(Config.data_path, '自定义文件', '机动导弹.json'))

    def open_file(self, file_path):
        # 获取选择的文件的索引
        index = self.model.index(file_path)

        if index.isValid():
            # 展开父项
            self.treeView_ToolBar.expand(index.parent())
            # 选择文件
            self.treeView_ToolBar.setCurrentIndex(index)
            self.scene.load_nodes(self.model.filePath(index))

    def handle_left_click(self, index):
        print(f"Left click on item: {self.model.filePath(index)}")

    def handle_double_left_click(self, index):
        print("index:", index)
        self.scene.load_nodes(self.model.filePath(index))
        print(f"Left Double click on item: {self.model.filePath(index)}")
